//
//  CCMineViewController.m
//  CwinCar
//
//  Created by dlios on 15/10/15.
//  Copyright © 2015年 dlios. All rights reserved.
//

#import "CCMineViewController.h"

@interface CCMineViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>

@end

@implementation CCMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的";
    [self creatImageArrray];
    [self creatCollectionView];
    [self creatTableViewController];
}
#pragma mark - 创建放置轮播图的图片数组及文字数组
-(void)creatImageArrray
{
     self.imgeArrary = [NSArray arrayWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg",@"6.jpg",@"7.jpg",@"8.jpg",@"9.jpg",@"10.jpg",@"11.jpg",@"12.jpg",@"13.jpg",@"14.jpg",@"15.jpg",@"16.jpg",@"17.jpg",@"18.jpg",@"19.jpg",@"20.jpg",@"21.jpg",@"22.jpg",@"23.jpg",@"24.jpg", nil];
    self.firstArray = [NSMutableArray arrayWithObjects:@"我的收藏",@"夜间模式",@"清除缓存", nil];
    self.secondArray = [NSMutableArray arrayWithObject:@"关于我们"];
    self.thirdArray = [NSMutableArray arrayWithObjects:@" ",@"  ", nil];
    
}
-(void)creatCollectionView
{
    TLCollectionViewLineLayout *flowLayout = [[TLCollectionViewLineLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(mainScreen_Width / 2.5, mainScree_Height / 3.705);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(mainScree_Height / 33.35, mainScreen_Width / 18.75, mainScree_Height / 33.35, mainScreen_Width / 18.75);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.imgCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, mainScreen_Width, mainScree_Height / 2.223)collectionViewLayout:flowLayout];
    self.imgCollectionView.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mainScreen_Width, mainScree_Height / 2.223)];
    UIImageView *backImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, mainScreen_Width, mainScree_Height / 2.223)];
    backImgView.image = [UIImage imageNamed:@"beijingtu"];
    [self.imgCollectionView.backgroundView addSubview:backImgView];
    self.imgCollectionView.showsHorizontalScrollIndicator = NO;
    self.imgCollectionView.delegate = self;
    self.imgCollectionView.dataSource = self;
    [self.view addSubview:self.imgCollectionView];
    [self.imgCollectionView registerClass:[CCMineCollectionViewCell class] forCellWithReuseIdentifier:@"CCMineCollectionViewCell"];
    
    
}
#pragma mark - 创建tableview delegate
-(void)creatTableViewController{
    self.mineTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, mainScreen_Width, mainScree_Height - 64) style:UITableViewStylePlain];
    self.mineTableView.delegate = self;
    self.mineTableView.dataSource = self;
    self.mineTableView.tableHeaderView = self.imgCollectionView;
    [self.mineTableView setBounces:NO];
    [self.view addSubview:self.mineTableView];
    //创建UISwitch按钮
    self.switchButton = [[UISwitch alloc]initWithFrame:CGRectMake(mainScreen_Width - 70, 10 * suitableScreen_Height, 55 * suitableScreen_Width, 25 * suitableScreen_Height)];
    self.switchButton.on = [[NSUserDefaults standardUserDefaults]boolForKey:@"nightMoon"];
    [self.switchButton addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
   
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.firstArray.count;
    }if (section == 1) {
        return 1;
    }
    return 0;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *str = [self.thirdArray objectAtIndex:section];
    return str;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return mainScree_Height / 14.822 + 14;
    }
    return mainScree_Height / 14.822;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cell";
    CCMineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[CCMineTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    //赋值
    if (indexPath.section == 0) {
        cell.titleLable.text = self.firstArray[indexPath.row];
        switch (indexPath.row ) {
            case 0:
                cell.imgeView.image = [UIImage imageNamed:@"iconfont-yishoucang"];
                break;
            case 1:
                cell.imgeView.image = [UIImage imageNamed:@"iconfont-yejianzhuanhuan"];
                [cell.contentView addSubview:self.switchButton];
                break;
                case 2:
                cell.imgeView.image = [UIImage imageNamed:@"iconfont-qingchuhuancun"];
                break;
            default:
                break;
        }
    }else
    {
        cell.titleLable.text = self.secondArray[indexPath.row];
        cell.imgeView.image = [UIImage imageNamed:@"iconfont-guanyuwomenicon"];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
#pragma mark - tableview的实现点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            MineCollectionViewController *mineCVC = [[MineCollectionViewController alloc]init];
            mineCVC.hidesBottomBarWhenPushed = YES ; 
            [self.navigationController pushViewController:mineCVC animated:YES];
        }
        if (indexPath.row == 2) {
            
            
            NSString *string = [NSString stringWithFormat:@"一共有%ld个文件可以清除",[self numberOfFile]];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除缓存" message:string preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
             [self myClearCacheAction];
        }];
            [alertController addAction:defaultAction];
            [self presentViewController:alertController animated:YES completion:nil];
    }
    }else if (indexPath.section == 1)
    {
        CCMineAboutViewController *aboutVC = [[CCMineAboutViewController alloc]init];
        aboutVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:aboutVC animated:YES];
    }
}
-(NSInteger)numberOfFile
{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];//此操作是找到  caches文件
    NSArray *files = [[NSFileManager defaultManager]subpathsAtPath:cachPath];
    return [files count];
}
-(void)myClearCacheAction
{
    //多线程 GCD
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //进行清除数据库
        //获取沙盒路径
        //参数1 路径参数(哪个文件)
        //参数2 搜索范围
        //参数3 绝对/相对
        //document  //进行清除数据库
        //获取沙盒路径
        //参数1 路径参数(哪个文件)
        //参数2 搜索范围
        //参数3 绝对/相对
        //document librarylibrary   caches
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];//caches找到
        NSArray *files =[[NSFileManager defaultManager]subpathsAtPath:cachPath];//获取caches下所有的文件夹 放在数组里
        for (NSString *p in files) {
            NSError *error;
            
            NSString *path = [cachPath stringByAppendingPathComponent:p];//拼接字符串
            if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
                [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
            }
        }
        [self performSelectorOnMainThread:@selector(clearCachSuccess) withObject:nil waitUntilDone:YES];
        
    });
}
-(void)clearCachSuccess
{
    self.alertView = [[UIAlertView alloc]initWithTitle:nil message:@"成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
    [self.alertView show];
 
}
-(void)performDismiss:(NSTimer *)timer
{
    [self.alertView dismissWithClickedButtonIndex:0 animated:NO];
}
#pragma mark - 轮播图collectionview协议方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imgeArrary.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CCMineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CCMineCollectionViewCell" forIndexPath:indexPath];
    //给items赋图片
    NSString *str = self.imgeArrary[indexPath.row];
    cell.collectionImgViwe.image = [UIImage imageNamed:str];
    return cell;
}
#pragma mark - 创建夜间模式
-(void)switchValueChange:(UISwitch *)swith
{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:swith.on forKey:@"nightmoon"];
    // //同步存储 当你处理逻辑比较复杂的时候 或者连续使用多个UserDefaults存入 同步存储会保证存储成功
    [defaults synchronize];
    //发送通知  ->发送夜间模式消息
    [[NSNotificationCenter defaultCenter] postNotificationName:@"night" object:nil];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
